<template>
  <el-dialog v-model="visible" :title="`手动配货 - ${selectedOrder.spuName || ''}`" width="800px">
    <!-- 物料信息摘要 -->
    <div class="spu-summary">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="物料编码">{{ selectedOrder.spuNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="物料名称">{{ selectedOrder.spuName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="要求数量">{{ requireStock || 0.000
          }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 配货进度 -->
    <div class="allocation-progress">
      <el-progress :percentage="allocationPercentage" :color="progressColor" :status="progressStatus" />
      <div class="allocation-stats">
        <span>已分配: <strong>{{ totalAllocated }}</strong></span>
        <span>待分配: <strong>{{ remainingToAllocate }}</strong></span>
      </div>
    </div>

    <!-- 仓库库存分配列表 -->
    <div class="allocation-table">
      <el-table 
        :data="stockList" 
        border
        height="300px"
        style="width: 100%"
      >
        <el-table-column prop="contNo" label="容器条码" width="120" />
        <el-table-column prop="locationNo" label="库位" width="150" />
        <el-table-column prop="spuNo" label="物料编号" width="150" />
        <el-table-column prop="stockQty" label="可用库存" width="100">
          <template #default="{ row }">
            <span :class="{ 'low-stock': row.stockQty < row.allocated }">
              {{ row.stockQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="分配数量" width="200">
          <template #default="{ row }">
            <el-input-number v-model="row.allocated" :step="1" :min="0" :max="row.stockQty" :precision="3"
              size="small" controls-position="right" @change="handleAllocationChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button type="danger" icon="Delete" circle size="small" @click="clearAllocation(row)" />
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="无可用库存" />
        </template>
      </el-table>
    </div>

    <!-- 分配合计 -->
    <div class="allocation-summary">
      <el-tag type="success" size="large">
        已分配: {{ totalAllocated }} / 要求: {{ requireStock || 0.000 }}
      </el-tag>
      <el-tag v-if="remainingToAllocate > 0" type="warning" size="large">
        待分配: {{ remainingToAllocate }}
      </el-tag>
      <el-tag v-if="Number(totalAllocated) > Number(requireStock)" type="danger" size="large">
        超额分配: {{ totalAllocated - requireStock }}
      </el-tag>
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="totalAllocated != requireStock" @click="handleConfirm">
        确认分配
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { getAllocationStock, allocation } from "@/api/wms/obDetails";
import { ElMessage } from 'element-plus'
import { ref, computed, watch} from 'vue';
const props = defineProps({
  selectedOrder: Object  // 包含物料信息和要求数量
})
const visible = defineModel()
const emit = defineEmits(['confirm'])
// 当前选中的物料信息

// 仓库库存数据
const stockList = ref([]);

// 计算总分配数量
const totalAllocated = computed(() => {
  return stockList.value.reduce((sum, item) => sum + item.allocated, 0).toFixed(3);
});

const requireStock = computed(() => {
  return (props.selectedOrder.obPlanQty - props.selectedOrder.obBindQty).toFixed(3)
})

// 计算待分配数量
const remainingToAllocate = computed(() => {
  return Math.max(0, requireStock.value - totalAllocated.value).toFixed(3);
});

// 计算分配进度百分比
const allocationPercentage = computed(() => {
  if (!requireStock.value) return 0;
  const percentage = (totalAllocated.value / requireStock.value) * 100;
  return Math.min(100, Math.round(percentage));
});

// 进度条颜色状态
const progressColor = computed(() => {
  if (totalAllocated.value < requireStock.value) return '#e6a23c';
  if (totalAllocated.value === requireStock.value) return '#67c23a';
  return '#f56c6c';
});

// 进度条状态
const progressStatus = computed(() => {
  if (totalAllocated.value < requireStock.value) return 'warning';
  if (totalAllocated.value === requireStock.value) return 'success';
  return 'exception';
});

// 处理分配数量变化
const handleAllocationChange = (row) => {
  
};

// 清除单行分配
const clearAllocation = (row) => {
  row.allocated = 0;
};

    // 确认分配
    const handleConfirm = async () => {
      // 构造分配结果
      const allocationResult = {
        obDetailId: props.selectedOrder.obDetailId,
        stocks: stockList.value.filter(item => item.allocated > 0).map(item => ({
          stockId: item.stockId,
          allotQty: item.allocated
        })),
      };
      const res = await allocation(allocationResult)
      if (res.code === 200) {
        ElMessage.success('手动配货成功！')
        visible.value = false
        emit('confirm', allocationResult);
        // 重置分配数据
        stockList.value.forEach(item => item.allocated = 0.000);
      } else {
        ElMessage.error(res.msg)
      }
    };

   const getStockList = async () => {
    const res = await getAllocationStock({
      spuNo: props.selectedOrder.spuNo
    })
    stockList.value = res.data
    stockList.value.forEach((item) => {
      item.allocated = 0.000
    })
   }
   getStockList()
</script>

<style scoped>
.spu-summary {
  margin-bottom: 20px;
}

.allocation-progress {
  margin: 20px 0;
}

.allocation-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 14px;
}

.allocation-table {
  margin: 20px 0;
}

.allocation-summary {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}

.el-tag {
  font-size: 14px;
  padding: 0 12px;
  height: 32px;
  line-height: 32px;
}
</style>